module Dephine

  # Public: Make a simple Command Line Interface.
  # To use this class the 'start' class method should be called.
  #
  # Examples
  #
  #   CLI.start(ARGV)
  #   # => nil
  class CLI

    # Public: Use cli arguments for running the application.
    #
    # Returns nothing.
    def self.start(args)
      banner = []
      banner << 'Dephine, Google dictionary in terminal'
      banner << 'Usage: dephine [word]'

      if args.empty?
        puts banner.join("\n")
      else
        define(args[0])
      end
    end

    # Public: Cross-platform way of finding an executable in the $PATH.
    #
    #   which('ruby') #=> /usr/bin/ruby
    def self.which(cmd)
      exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
      ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
        exts.each { |ext|
          exe = "#{path}/#{cmd}#{ext}"
          return exe if File.executable? exe
        }
      end
      return nil
    end

    # Public: Play word pronunciation.
    # This method uses either mpg123 or afplay to play the audio file.
    #
    # audio - The String that should be path of an audio file to be played.
    def self.play(audio)
      player = which('mpg123') || which('afplay')
      system("#{player} #{audio} 2>/dev/null")
    end

    # Internal: Display definitions of a word.
    #
    # arg - The String that will be defined.
    def self.define(arg)
      word = Dephine::Dictionary.new(arg)

      if word.meanings.empty?
        abort("Word not found in the dictionary!")
      end

      t = Dephine::TUI.new
      t.puts arg

      word.meanings.each do |m|
        t.puts
        t.puts "#{m[:type].downcase} #{m[:phonetic]}"
        m[:meanings].each do |d|
          t.puts "  #{d[:text]}"
          d[:examples].each do |eg|
            t.puts "    - #{eg}"
          end
          t.puts
        end
      end

      if word.pronunciations.length > 0
        # download pronunciation audio file
        open(word.pronunciations[0][:url])
        pronunciation = OpenURI::Cache.send(:filename_from_url, word.pronunciations[0][:url])

        # play pronunciation
        t.set_key 'p' do
          play(pronunciation)
        end
      end

      t.close

    end

    class << self
      private :define
    end

  end
end
